//
//  FindPsdViewController.m
//  DatePickTest
//
//  Created by user on 15/8/13.
//  Copyright (c) 2015年 user. All rights reserved.
//
#import "FindPsdViewController.h"
#import "ResetPsdViewController.h"

@interface FindPsdViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) UITextField * phoneTextField;//用户名
@property (nonatomic,strong) UITextField * verifiCodeTextField;//验证码
@property (nonatomic,strong) UIButton    * verifiCodeBtn;//发送验证码按钮
@property (nonatomic,assign) int           statusInt;
@property (nonatomic,strong) NSTimer     * timer;
@end

@implementation FindPsdViewController
-(void)dealloc
{
    [_timer invalidate];
    self.timer = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _statusInt = 60;
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];

    [self createTheNavigationBar];//创建导航栏
    [self createTheInformationView];
    
}
#pragma mark ------------创建导航栏
-(void)createTheNavigationBar
{
    [[UIApplication sharedApplication]setStatusBarHidden:FALSE];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    [self.view addSubview:topView];
    //标题
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0.0f, 20.0f, SCREEN_WIDTH, 44.0f)];
    titleLab.backgroundColor = [UIColor clearColor];
    titleLab.font = [UIFont boldSystemFontOfSize:20.0f];
    titleLab.textColor = [UIColor whiteColor];
    titleLab.text = @"忘记密码";
    titleLab.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:titleLab];
    
    //返回按钮
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];;
    
    
}
#pragma mark--------------创建用户信息view
-(void)createTheInformationView
{
   
    UIView * userView = [[UIView alloc]initWithFrame:CGRectMake(0, 64 + 10*HSCALE, SCREEN_WIDTH , 88*HSCALE)];
    userView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userView];
    
    UILabel * userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 70, 40*HSCALE)];
    userNameLabel.text = @"手机号码";
    userNameLabel.textColor = RGBA(99, 98, 99, 1);
    userNameLabel.textAlignment = NSTextAlignmentLeft;
    [userView addSubview:userNameLabel];
    
    _phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(90, 0.0f, SCREEN_WIDTH - 180, 40*HSCALE)];
    _phoneTextField.placeholder = @"注册使用的手机号码";
    _phoneTextField.delegate = self;
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;

    _phoneTextField.font = [UIFont systemFontOfSize:14];
    [userView addSubview:_phoneTextField];
    
    UIView * lineView1 = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 99, 10.0f *HSCALE, 1, 20*HSCALE)];
    lineView1.backgroundColor = [UIColor lightGrayColor];
    [userView addSubview:lineView1];
    
    _verifiCodeBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 100, 0.0f, 100, 40*HSCALE)];
    [_verifiCodeBtn setTitle:@"发送验证码 " forState:UIControlStateNormal];
    _verifiCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_verifiCodeBtn setTitleColor:[UIColor hexStringToColor:RED_COLOR_VALUE] forState:UIControlStateNormal];
    [_verifiCodeBtn addTarget:self action:@selector(buttonSendCodeTapped:) forControlEvents:UIControlEventTouchUpInside];
    [userView addSubview:_verifiCodeBtn];
    
    
    UIView * lineView2 = [[UIView alloc]initWithFrame:CGRectMake(10*WSCALE, 41*HSCALE, SCREEN_WIDTH - 20*WSCALE, 1*HSCALE)];
    lineView2.backgroundColor = RGBA(240, 240, 240, 1);
    [userView addSubview:lineView2];
    
    UILabel * psdLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 42*HSCALE, 90, 40*HSCALE)];
    psdLabel.text = @"输入验证码";
    psdLabel.textColor = RGBA(99, 98, 99, 1);
    psdLabel.textAlignment = NSTextAlignmentLeft;
    [userView addSubview:psdLabel];
    
    _verifiCodeTextField = [[UITextField alloc]initWithFrame:CGRectMake(110, 42*HSCALE, SCREEN_WIDTH - 120, 40*HSCALE)];
    _verifiCodeTextField.delegate = self;
    _verifiCodeTextField.font = [UIFont systemFontOfSize:15];
    _verifiCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    _verifiCodeTextField.secureTextEntry = TRUE;
    [userView addSubview:_verifiCodeTextField];
    
    //下一步按钮
    UIButton * nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 20*WSCALE, 35*HSCALE)];
    nextBtn.center = CGPointMake(self.view.center.x, 64+142.5*HSCALE);
    nextBtn.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
    nextBtn.layer.cornerRadius = 5;
    nextBtn.layer.masksToBounds = TRUE;
    nextBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(buttonNextSetpTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
}
#pragma mark--------------下一步按钮绑定方法
-(void)buttonNextSetpTapped:(id)sender
{
    if (_phoneTextField.text.length <=0)
    {
        ALERT_VIEW(@"手机号码不能为空");
        return;
    }
    if (![self validateMobile:_phoneTextField.text])
    {
        ALERT_VIEW(@"手机号码不合法");
        return;
    }
    if (_verifiCodeTextField.text.length<=0)
    {
        ALERT_VIEW(@"验证码不能为空");
        return;
    }
   [self.view endEditing:TRUE];//让键盘下去
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

    //验证码是否有效
    [AppGlobalClass PostDataWithNSstring:REGIST_ISRIGHT withDictionary:@{@"mobileNumber":_phoneTextField.text,@"checkCode":_verifiCodeTextField.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            ResetPsdViewController * vc = [[ResetPsdViewController alloc]initWithPhoneNum:_phoneTextField.text];
            [self presentViewController:vc animated:TRUE completion:nil];
        }else
        {
            //无效的话，进行弹框提示
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } networkerror:^(NSString *networkerror) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    }];
    }
#pragma mark--------------发送验证码
-(void)buttonSendCodeTapped:(id)sender
{
    if (_phoneTextField.text.length<=0)
    {
        ALERT_VIEW(@"请输入手机号码");
        return;
    }
    if (![self validateMobile:_phoneTextField.text])
    {
        ALERT_VIEW(@"手机号码不合法");
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    
    [AppGlobalClass PostDataWithNSstring:PHONE_ISREGIST withDictionary:@{@"mobile":_phoneTextField.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:FALSE]])
        {
            [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
            NSString * string = [dictionary objectForKey:@"message"];
            ALERT_VIEW(string);
        }else
        {//注册的时候
            UIButton * sendBtn = (UIButton *)sender;
            sendBtn.enabled = FALSE;
            [sendBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            
            [AppGlobalClass PostDataWithNSstring:REGIST_CODE withDictionary:@{@"mobileNumber":_phoneTextField.text} success:^(NSDictionary *dictionary) {
                if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
                {
                    if (!_timer)
                    {
                        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:TRUE];//开启定时器  倒计时结束后，在倒计时方法内使得按钮可以点击
                        [_timer fire];
                    }
                }
                [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
                
            } failure:^(NSError *error) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
                sendBtn.enabled = TRUE;
            } networkerror:^(NSString *networkerror) {
                sendBtn.enabled = TRUE;
                [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
                
            }];

        }
        
    } failure:^(NSError *error) {
          [MBProgressHUD hideHUDForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror) {
          [MBProgressHUD hideHUDForView:self.view animated:TRUE];
    }];
 
    
    
}
#pragma mark--------------返回按钮绑定方法
-(void)buttonBackTapped:(id)sender
{
    [self dismissViewControllerAnimated:TRUE completion:nil];
}
    //时间倒计时
-(void)timeCounting
{
    
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    if ([phoneVersion doubleValue] > 8.0)
    {
        [_verifiCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重试",_statusInt] forState:UIControlStateNormal];
    }
    else
    {
        _verifiCodeBtn.titleLabel.frame =CGRectMake(0, 0, _verifiCodeBtn.frame.size.width, _verifiCodeBtn.frame.size.height);
        _verifiCodeBtn.titleLabel.text = [NSString stringWithFormat:@"%d秒后重试",_statusInt] ;
    }
        
    if(_statusInt == 0)
    {
        if ([phoneVersion doubleValue] > 8.0)
        {
            [_verifiCodeBtn setTitle:@" 重新获取 " forState:UIControlStateNormal];
        }
        else
        {
            _verifiCodeBtn.titleLabel.frame =CGRectMake(0, 0, _verifiCodeBtn.frame.size.width, _verifiCodeBtn.frame.size.height);
            _verifiCodeBtn.titleLabel.text = @" 重新获取 " ;
        }
        _statusInt = 60;
        _verifiCodeBtn.enabled = TRUE;
        _verifiCodeBtn.titleLabel.textColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        [_verifiCodeBtn setTitleColor:[UIColor hexStringToColor:RED_COLOR_VALUE] forState:UIControlStateNormal];
        [_timer invalidate];
        _timer = nil;
        return;
    }
    _statusInt -=1;
}
#pragma mark--------textFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (_phoneTextField == textField)
    {
        NSString *a = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (a.length>11) {
            
            return NO;
        }
        return YES;
    }else
    {
        NSString *a = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (a.length>18) {
            
            return NO;
        }
        return YES;
    }
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//手机号码验证
-(BOOL)validateMobile:(NSString *)mobile
{
    //手机号以13，14, 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^(1[0-9])\\d{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
